package com.flycms.modules.group.controller.front;

import com.flycms.common.constant.UserConstants;
import com.flycms.common.utils.SessionUtils;
import com.flycms.common.utils.StrUtils;
import com.flycms.common.utils.bean.BeanConvertor;
import com.flycms.framework.aspectj.lang.annotation.Log;
import com.flycms.framework.aspectj.lang.enums.BusinessType;
import com.flycms.framework.web.controller.BaseController;
import com.flycms.framework.web.domain.AjaxResult;
import com.flycms.modules.group.domain.Group;
import com.flycms.modules.group.domain.GroupTopicColumn;
import com.flycms.modules.group.domain.GroupUser;
import com.flycms.modules.group.domain.dto.GroupColumnDTO;
import com.flycms.modules.group.domain.dto.GroupDTO;
import com.flycms.modules.group.service.IGroupColumnService;
import com.flycms.modules.group.service.IGroupService;
import com.flycms.modules.group.service.IGroupTopicColumnService;
import com.flycms.modules.group.service.IGroupUserService;
import com.flycms.modules.user.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

/**
 * 小组相关Controller
 * 
 * @author admin
 * @date 2020-07-08
 */
@Controller
public class GroupController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(GroupController.class);

    @Autowired
    private IGroupService groupService;

    @Autowired
    private IGroupColumnService groupColumnService;

    @Autowired
    private IGroupUserService groupUserService;

    @Autowired
    private IGroupTopicColumnService groupTopicColumnService;

    /////////////////////////////////
    ///////       增加       ////////
    /////////////////////////////////
    /**
     * 新增群组(小组)
     */
    @GetMapping("/user/group/create")
    public String add(Group group,ModelMap modelMap)
    {
        User user = SessionUtils.getUser();
        if(user == null){
            return forward("/user/login");
        }
        return theme.getPcTemplate("/group/create");
    }

    /**
     * 新增群组(小组)
     */
    @PostMapping("/user/group/create")
    @ResponseBody
    public AjaxResult add(Group group) throws Exception
    {
        User user = SessionUtils.getUser();
        if(user == null){
            return AjaxResult.error("未登录或者用户不存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(groupService.checkGroupGroupNameUnique(group)))
        {
            return AjaxResult.error("新增群组(小组)'" + group.getGroupName() + "'失败，群组名称已存在");
        }
        group.setUserId(user.getId());
        return toAjax(groupService.insertGroup(group));
    }

    /**
     * 新增群组和用户对应关系
     */
    @PostMapping("/group/user/follow")
    @ResponseBody
    public AjaxResult add(GroupUser groupUser)
    {
        User user = SessionUtils.getUser();
        if(user == null){
            return AjaxResult.error(101,"请登录后关注");
        }
        return groupUserService.insertGroupUser(groupUser);
    }

    /**
     * 新增帖子分类
     */
    @ResponseBody
    @PostMapping("/user/group/addcolumn")
    public AjaxResult addTopicColumn(GroupTopicColumn groupTopicColumn)
    {
        User user = SessionUtils.getUser();
        if(user == null){
            return AjaxResult.error("未登录或者用户不存在");
        }
        if (groupTopicColumn.getGroupId()==null) {
            return AjaxResult.error("小组id不能为空");
        }
        Group content= groupService.findGroupById(groupTopicColumn.getGroupId());
        if(content == null){
            return AjaxResult.error("小组不存在！");
        }
        if (UserConstants.NOT_UNIQUE.equals(groupTopicColumnService.checkGroupTopicColumnUnique(groupTopicColumn)))
        {
            return AjaxResult.error("新增小组分类'" + groupTopicColumn.getColumnName() + "'失败，分类名称已存在");
        }
        GroupUser findgroupUser = new GroupUser();
        findgroupUser.setGroupId(groupTopicColumn.getGroupId());
        findgroupUser.setUserId(user.getId());
        GroupUser userDTO=groupUserService.findGroupUser(findgroupUser);
        if(userDTO == null || userDTO.getStatus() == 0){
            return AjaxResult.error("用户未加入或者加入申请未审核");
        }
        if(userDTO.getIsfounder() != 1){
            return AjaxResult.error(403,"只有小组创始人才能添加分类");
        }
        groupTopicColumn.setUserId(user.getId());
        return toAjax(groupTopicColumnService.insertGroupTopicColumn(groupTopicColumn));
    }

    /////////////////////////////////
    ///////        修改      ////////
    /////////////////////////////////
    /**
     * 圈子用户管理后台
     *
     * @return
     */
    @GetMapping("/user/group/{groupId}/setting/user/")
    public String groupUser(@PathVariable("groupId") String groupId,
                            @PathVariable(value = "p", required = false) String p,
                            ModelMap modelMap){
        if (!StrUtils.checkLong(groupId)) {
            return forward("error/404");
        }
        Group content= groupService.findGroupById(Long.valueOf(groupId));
        if(content == null){
            return forward("error/404");
        }
        if(p == null) p = "1";
        modelMap.addAttribute("groupId", groupId);
        modelMap.addAttribute("p", p);
        modelMap.addAttribute("content", BeanConvertor.convertBean(content, GroupDTO.class));
        return theme.getPcTemplate("group/group_user");
    }

    /**
     * 修改小组基本信息
     *
     * @return
     */
    @GetMapping("/user/group/{groupId}/setting/profile/")
    public String groupProfile(@PathVariable("groupId") String groupId,
                               @PathVariable(value = "p", required = false) String p,
                               ModelMap modelMap){
        if (!StrUtils.checkLong(groupId)) {
            return forward("error/404");
        }
        Group content= groupService.findGroupById(Long.valueOf(groupId));
        if(content == null){
            return forward("error/404");
        }
        if(p == null) p = "1";
        modelMap.addAttribute("groupId", groupId);
        modelMap.addAttribute("p", p);
        modelMap.addAttribute("content", BeanConvertor.convertBean(content, GroupDTO.class));
        return theme.getPcTemplate("group/group_profile");
    }

    /**
     * 小组分类管理
     *
     * @return
     */
    @GetMapping("/user/group/{groupId}/setting/classify/")
    public String groupBasic(@PathVariable("groupId") String groupId,
                             @PathVariable(value = "p", required = false) String p,
                             ModelMap modelMap){
        if (!StrUtils.checkLong(groupId)) {
            return forward("error/404");
        }
        Group content= groupService.findGroupById(Long.valueOf(groupId));
        if(content == null){
            return forward("error/404");
        }
        if(p == null) p = "1";
        modelMap.addAttribute("groupId", groupId);
        modelMap.addAttribute("p", p);
        modelMap.addAttribute("content", BeanConvertor.convertBean(content, GroupDTO.class));
        return theme.getPcTemplate("group/group_classify");
    }

    /**
     * 新增群组(小组)
     */
    @PostMapping("/user/group/basic")
    @ResponseBody
    public AjaxResult add(@RequestParam(value = "id", required = false) String id,
                          @RequestParam(value = "groupName", required = false) String groupName,
                          @RequestParam(value = "groupDesc", required = false) String groupDesc,
                          @RequestParam(value = "photo", required = false) String photo,
                          @RequestParam(value = "bgphoto", required = false) String bgphoto,
                          @RequestParam(value = "isopen", required = false) String isopen,
                          @RequestParam(value = "roleLeader", required = false) String roleLeader,
                          @RequestParam(value = "roleAdmin", required = false) String roleAdmin,
                          @RequestParam(value = "roleUser", required = false) String roleUser){

        Group group = new Group();
        group.setId(Long.valueOf(id));
        group.setGroupName(groupName);
        group.setGroupDesc(groupDesc);
        group.setPhoto(photo);
        group.setBgphoto(bgphoto);
        group.setIsopen(isopen);
        group.setRoleLeader(roleLeader);
        group.setRoleAdmin(roleAdmin);
        group.setRoleUser(roleUser);
        groupService.updateGroup(group);
        return AjaxResult.success();
    }

    /////////////////////////////////
    ///////        查詢      ////////
    /////////////////////////////////
    /**
     * 首页
     *
     * @return
     */
    @GetMapping(value = {"/group/","/group-index","/group-inedx-p-{p}","/group-column-{columnId}","/group-column-{columnId}/","/group-column-{columnId}-p-{p}"})
    public String groupList(@PathVariable(value = "columnId", required = false) String columnId,
                            @PathVariable(value = "p", required = false) String p,
                            ModelMap modelMap){
        if(!StrUtils.isEmpty(columnId)){
            if (!StrUtils.checkLong(columnId)) {
                return forward("error/404");
            }
            GroupColumnDTO column=groupColumnService.findGroupColumnById(Long.valueOf(columnId));
            if(column == null){
                return forward("error/404");
            }
            modelMap.addAttribute("column", column);
        }
        if(p == null) p = "1";
        modelMap.addAttribute("p", p);
        modelMap.addAttribute("columnId", columnId);
        return theme.getPcTemplate("group/list_group");
    }

    /**
     * 圈子详情页面
     *
     * http://127.0.0.1:8080/g-jiemeng
     * http://127.0.0.1:8080/g-jiemeng-2
     *
     * @return
     */
    @GetMapping(value = {"/g-{shortUrl:\\w+}","/g-{shortUrl:\\w+}-{p:\\d+}","/g-{shortUrl:\\w+}-t-{column:\\w+}","/g-{shortUrl:\\w+}-t-{column:\\w+}-{p:\\d+}"})
    public String groupShowPager(@PathVariable(value = "shortUrl", required = false) String shortUrl,
                                 @PathVariable(value = "column", required = false) String column,
                            @PathVariable(value = "p", required = false) String p
            , ModelMap modelMap){
        if (StrUtils.isEmpty(shortUrl)) {
            return forward("error/404");
        }
        Group content= groupService.findGroupByShorturl(shortUrl);
        if(content == null){
            return forward("error/404");
        }
        Long columnId = null;
        if (!StrUtils.isEmpty(column)) {
            if("0".equals(column)){
                columnId = 0l;
            }else{
                GroupTopicColumn entity= groupTopicColumnService.findGroupTopicColumnByShorturl(column);
                if(entity != null){
                    columnId = entity.getId();
                }else{
                    return forward("error/404");
                }
            }
        }

        if(p == null) p = "1";
        modelMap.addAttribute("groupId", content.getId());
        modelMap.addAttribute("columnId", columnId);
        modelMap.addAttribute("columnUrl", column);
        modelMap.addAttribute("p", p);
        modelMap.addAttribute("content", BeanConvertor.convertBean(content, GroupDTO.class));
        return theme.getPcTemplate("group/detail");
    }

    /**
     * 小组分类管理
     *
     * @return
     */
    @GetMapping(value = {"/user/g-{shortUrl}/topic-list","/user/g-{shortUrl}/topic-list-{p}"})
    public String groupTopicList(@PathVariable("shortUrl") String shortUrl,
                             @PathVariable(value = "p", required = false) String p,
                             ModelMap modelMap){
        if (StrUtils.isEmpty(shortUrl)) {
            return forward("error/404");
        }
        Group content= groupService.findGroupByShorturl(shortUrl);
        if(content == null){
            return forward("error/404");
        }
        if(p == null) p = "1";
        User user = SessionUtils.getUser();
        GroupUser groupUser = new GroupUser();
        groupUser.setGroupId(content.getId());modelMap.addAttribute("p", p);
        groupUser.setUserId(user.getId());
        groupUser.setIsadmin(2);
        groupUser.setStatus(2);
        GroupUser admin = groupUserService.findGroupUser(groupUser);
        if(admin == null){
            return forward("error/404");
        }


        modelMap.addAttribute("content",content);
        return theme.getPcTemplate("group/group_list_topic");
    }


}
